package libraries;

import java.io.File;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.lang.Object;

import java.util.Vector;

import javax.swing.ImageIcon;

import javax.swing.JPanel;

import GUI.BDErrorMsg;
import GUI.JFrameBase;
import GUI.InterErrorMsg;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import model.DB2Hash;


public class LanguageLibrary {
    
    // CONEXIONES
    //InterErrorMsg IEM = new BDErrorMsg(); 
    MultimediaLibrary Lib = MultimediaLibrary.getInstance();
    private FunctionLibrary FL = new FunctionLibrary();
    
    // DEFINICIöN DE LOS IMAGEICON
    ImageIcon error = Lib.getImageIcon(6);
    ImageIcon tick = Lib.getImageIcon(7);
    ImageIcon info = Lib.getImageIcon(10);
    
    // DEFINICIÓN DE VARIABLES
    public int longitudMsg;
    
    
    public LanguageLibrary() {
        
    }
          
    public void getLongitudMsg(int longitudMsg){        
        this.longitudMsg = longitudMsg;
    }

    public Object[] getError(int input){
        String texto = "";
        ImageIcon icono = null;
        /*
         * SIGNIFICADO DE CADA ERROR
         * ----------------------------------------------------
         * 0: CONTRASEÑA INCORRECTA;
         */
        switch(input){
            case(0): texto = "Faltan campos de datos por rellenar";
                     icono = error;
                break;                           
            case(1): texto = "Introduzca la contraseña para almacenar los cambios.";
                     icono = error;
                break;
            case(2): texto = "La contraseña introducida no es válida";
                     icono = error;
                break;
            case(3): texto = "Configuración guardada con éxito";
                     icono = tick;
                break;
            case (4):
                texto = "ERROR BD: No se pudo leer la base de datos";
                     icono = tick;
                break;
            case(5): texto = "ERROR BD: No se pudo escribir en la base de datos (revise datos de entrada)";
                     icono = tick;
                break;
            case(6): texto = "ERROR CONFIGURANDO EQUIPO: En la red no se ha localizado ningún equipo con la IP especificada";
                     icono = tick;
                break;
            case(7): texto = "ERROR CONFIGURANDO SERVIDOR: En la red no se ha localizado ningún equipo con la IP especificada";
                     icono = tick;
                break;
            case(8): texto = "Configuración IP correcta";
                     icono = tick;
                break;
            case(9): texto = "Introduzca la contraseña";
                     icono = tick;
                break;
            case(10): texto = "Faltan campos de datos por rellenar en la sección 'Gestión de usuarios'";
                     icono = tick;
                break;
            case(11): texto = "Faltan campos de datos por rellenar en la sección 'Configuración del servidor PACS'";
                     icono = tick;
                break;
            case(12): texto = "No existe ninguna configuración definida para usuarios del software";
                     icono = tick;
                break;
            case(13): texto = "No existe ninguna configuración definida para servidores PACS";
                     icono = tick;
                break;
            case(14): texto = "El valor de UID asignado al dispositivo no es válido.\n- Revise si ha escrito un carácter no permitido.";
                     icono = tick;
                break;
        }
        Object output[] = new Object []{texto,icono};
        return output;
    }

    public Object[] getImageError(int input){
        String texto = "";
        ImageIcon icono = null;
        /*
         * SIGNIFICADO DE CADA ERROR
         * ----------------------------------------------------
         * 0: NO SE HA SELECCIONADO IMAGEN;
         */
        switch(input){
            case(0): texto = "NO SE HA CARGADO NINGUNA IMAGEN";
                     icono = error;
                break;
        }
        Object output[] = new Object []{texto,icono};
        return output;
    }
    
    public String[] getUID(){
        String[] modality = {"1.2.840.10008.5.1.4.1.1.80.1",
                            "1.2.840.10008.5.1.4.1.1.77.1.4",
                            "1.2.840.10008.5.1.4.1.1.77.1.5.1",
                            "1.2.840.10008.5.1.4.1.1.77.1.5.2",
                            "1.2.840.10008.5.1.4.1.1.77.1.5.3",
                            "1.2.840.10008.5.1.4.1.1.77.1.5.4",

                            "1.2.840.10008.5.1.4.1.1.78.4",
                            "1.2.840.10008.5.1.4.1.1.78.5",

                            "1.2.840.10008.5.1.4.1.1.79.1",
                            "1.2.840.10008.5.1.4.1.1.104.1"};
        return modality;
    }

    public Object[] displayUIDMeaning(int input){
        String texto = "";
        ImageIcon icono = null;

        switch(input){
                    case (0):texto = "Campo Visual Oftálmico: \nAlmacena las medidas de Perimetría Estática"; //texto = "Ophthalmic Visual Field – Static Perimetry Measurements Storage";
                             break;
                    case(1): texto = "Almacenamiento de imagen fotográfica VL";  //texto = "VL Photographic Image Storage";
                             break;
                    case(2): texto = "Almacenamiento de imagen Oftálmica de 8 bits";  //texto = "Ophthalmic 8 bit Photography Image Storage";
                             break;
                    case(3): texto = "Almacenamiento de imagen Oftálmica de 16 bits";   //texto = "Ophthalmic 16 bit Photography Image Storage";
                             break;
                    case(4): texto = "Almacenamiento de la Relación Estereométrica: \n Fusión de imágenes en estéreo";   //texto = "Stereometric Relationship Storage";
                             break;
                    case(5): texto = "Almacenamiento de imagen de OCT \n(Ophthalmic Coherence Tomography)";    //texto = "Ophthalmic Tomography  Image Storage";
                             break;
                    case(6): texto = "Almacenamiento de medidas de Refracción";  //texto = "Subjective Refraction Measurements Storage";
                             break;
                    case(7): texto = "Almacenamiento de medidas en Agudeza Visual";  //texto = "Visual Acuity Measurements Storage";
                             break;
                    case(8): texto = "Almacenamiento del informe de Volúmen y Grosor de la Mácula";    //texto = "Macular Grid Thickness and Volume Report";
                             break;
                    case(9): texto = "Almacenamiento de PDF Encapsulado";    //texto = "Encapsulated PDF Storage";
                             break;
        }
    icono = info;
    Object output[] = new Object []{ texto, icono};
    return output;
    }

    public String[] getAcquisitionDeviceType(){
        //String[] modality = {"R-1021A","A-2B201","R-1021B","R-1021C","A-2B210","A-00E8A","R-1021D","R-1021E","R-1021F","A-00FCA"};
        String[] modality = {"Retinógrafo","Biomicroscopio o lámpara de hendidura","Cámara externa","Microscopio especular",
                            "Microscopio operatorio","Oftalmoscopio de barrido láser","Oftalmoscopio indirecto","Oftalmoscopio directo",
                            "Endoscopio oftálmico","Keratoscopio"};
        return modality;
    }
    public ArrayList<String> getAcquisitionDeviceCID(String AcquisitionDevice){ // Perimeter case non included in DICOM standard.
        ArrayList<String> CID = new ArrayList<String>();    // 4202: Fundus camera
        String[] list = {"Retinógrafo","Biomicroscopio o lámpara de hendidura","Cámara externa","Microscopio especular",
                          "Microscopio operatorio","Oftalmoscopio de barrido láser","Oftalmoscopio indirecto","Oftalmoscopio directo",
                          "Endoscopio oftálmico","Keratoscopio"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(AcquisitionDevice);

        String[] CSD_list = {"SRT","SRT","SRT","SRT","SRT","SRT","SRT","SRT","SRT","SRT"};
        String[] CV_list =  {"R-1021A","A-2B201","R-1021B","R-1021C","A-2B210","A-00E8A","R-1021D","R-1021E","R-1021F","A-00FCA"};
        String[] CM_list =  {"Fundus Camera","Slit Lamp Biomicroscope","External Camera","Specular Microscope",
                            "Operating Microscope","Scanning Laser Ophthalmoscope","Indirect Ophthalmoscope","Direct Ophthalmoscope",
                            "Ophthalmic Endoscope","Keratoscope"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.318";

        System.out.println("TestType: "+AcquisitionDevice+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);
        return CID;
    }

    public ArrayList<String> getProtocolContextCID(String value){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4236
        String[] list = {"","Screening","Diagnóstico"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(value);

        String[] CSD_list = {"","SRT","SRT"};
        String[] CV_list =  {"","R-42453","R-408C3"};
        String[] CM_list =  {"","Screening","Diagnostic"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.915";

        System.out.println("Value: "+value+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);
        return CID;
    }
        
    public String[] getModality(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"OPV","OPT","XC","SC","OT"};            
        return modality;
    }

    public Object[] displayInfoModality(int input){
    /*
     *  FUNCIÓN DE CARGA DE MENSAJES + ICONO:
     *  SE GENERAN LOS MENSAJES EN FUNCIÓN DE LOS NÚMEROS DE ERROR.
     *  SE PUEDE AÑADIR UNA ENTRADA DE IDIOMA PARA CAMBIAR EL IDIOMA DE LOS MENSAJES.
     */
            
        String texto = "";    
        ImageIcon icono = null;
                        
        switch(input){
                    case(0): texto = "Campimetría (OPV)";
                             icono = tick;
                             break;
                    case(1): texto = "Tomografía óptica de coherencia (OPT)";
                             icono = tick;
                             break;
                    case(2): texto = "Retinografías simples (XC)";
                             icono = error;
                             break;
                    case(3): texto = "Mosaico compuesto de retinografías (SC)";
                             icono = error;
                             break;
                    case(4): texto = " Cualquier modalidad de imagen que no aparezca en la lista (OT)." +
                                     "\n Para incluir la modalidad escríbala en el recuadro. Si el recuadro" +
                                     " está vacío, por defecto se asignará el valor 'OT'.";
                             icono = error;
                             break;
                                                                       
        } 
    Object output[] = new Object []{ texto, icono};  
    return output;    
    }

    public String[] getTestType(){
        // Lista de modalidades con las que nos vamos a encontrar.
        //String[] modality = {"","Central 10-2","Central 24-2","Central 30-2","Periférico 60-4","Detección C-40","Detección C-76","Detección P-60","Detección CC-81","Detección CC-120"};
        // CID 4230
        String[] modality = {"","24-2","10-2","30-2","60-4","Mácula","Central 40 puntos","Central 76 puntos","Periféricos 60 puntos","Campo Completo 81 puntos","Campo Completo 120 puntos","G","M","07","LVC","Central"};
        return modality;
    }
    
    public ArrayList<String> getTestTypeCID(String TestType){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4230
        String[] TestType_list = {"","24-2","10-2","30-2","60-4","Mácula","Central 40 puntos","Central 76 puntos","Periféricos 60 puntos","Campo Completo 81 puntos","Campo Completo 120 puntos","G","M","07","LVC","Central"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(TestType_list));

        // Search for element in list
        int index = match_list.indexOf(TestType);
        
        String[] CSD_list = {"","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM"};
        String[] CV_list =  {"","111800","111801","111802","111803","111804","111805","111806","111807","111808","111809","111810","111811","111812","111813","111814"};
        String[] CM_list =  {"","Visual Field 24-2 Test Pattern","Visual Field 10-2 Test Pattern","Visual Field 30-2 Test Pattern",
                            "Visual Field 60-4 Test Pattern","Visual Field Macula Test Pattern","Visual Field Central 40 Point Test Pattern",
                            "Visual Field Central 76 Point Test Pattern","Visual Field Peripheral 60 Point Test Pattern",
                            "Visual Field Full Field 81 Point Test Pattern","Visual Field Full Field 120 Point Test Pattern",
                            "Visual Field G Test Pattern","Visual Field M Test Pattern","Visual Field 07 Test Pattern",
                            "Visual Field LVC Test Pattern","Visual Field Central Test Pattern"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.909";
        
        System.out.println("TestType: "+TestType+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);
        return CID;
    }
    
    public String[] getStrategy(){
        // Lista de modalidades con las que nos vamos a encontrar.
        // CID 4231
        //String[] modality = {"","SITA-Standard","SITA-Fast","Umbral completo","FastFac"};
        String[] modality = {"","SITA-Standard","SITA-Fast","SITA-SWAP","Umbral completo","FastFac","Anterior completo","Optima","Bi-zona","Tri-zona","Cuantificar-Defectos","TOP","Dinámico","Normal","1-LT","2-LT","LVS","GATE","GATEi","2LT-Dinámico","2LT-Normal","Fast Threshold","CLIP","CLASS"};
        return modality;
    }
    
    public ArrayList<String> getStrategyCID(String TestStrategy){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4231
        String[] TestStrategy_list = {"","SITA-Standard","SITA-SWAP","SITA-Fast","Umbral completo","FastFac","Anterior completo","Optima","Bi-zona","Tri-zona","Cuantificar-Defectos","TOP","Dinámico","Normal","1-LT","2-LT","LVS","GATE","GATEi","2LT-Dinámico","2LT-Normal","Fast Threshold","CLIP","CLASS"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(TestStrategy_list));

        // Search for element in list
        int index = match_list.indexOf(TestStrategy);

        String[] CSD_list = {"","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM","DCM"};
        String[] CV_list =  {"","111815","111816","111817","111818","111819","111820","111821","111822","111823","111824","111825","111826","111827","111828","111829","111830","111831","111832","111833","111834","111835","111836","111837"};
        String[] CM_list =  {"","Visual Field SITA-Standard Test Strategy","Visual Field SITA-SWAP Test Strategy","Visual Field SITA-Fast Test Strategy",
                            "Visual Field Full Threshold Test Strategy","Visual Field FastPac Test Strategy","Visual Field Full From Prior Test Strategy",
                            "Visual Field Optima Test Strategy","Visual Field Two-Zone Test Strategy","Visual Field Three-Zone Test Strategy",
                            "Visual Field Quantify-Defects Test Strategy","Visual Field TOP Test Strategy","Visual Field Dynamic Test Strategy",
                            "Visual Field Normal Test Strategy","Visual Field 1-LT Test Strategy","Visual Field 2-LT Test Strategy",
                            "Visual Field LVS Test Strategy","Visual Field GATE Test Strategy","Visual Field GATEi Test Strategy",
                            "Visual Field 2LT-Dynamic Test Strategy","Visual Field 2LT-Normal Test Strategy","Visual Field Fast Threshold Test Strategy",
                            "Visual Field CLIP Test Strategy","Visual Field CLASS Strategy"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.910";
        System.out.println("TestStrategy: "+TestStrategy+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);        
        return CID;
    }

    public String[] getTestMode(){
        // Lista de modalidades con las que nos vamos a encontrar.
        //String[] modality = {"Age-corrected","Threshold related","Single intensity"};
        // CID 4232
        //String[] modality = {"","Prueba de umbral","Edad corregida","Intensidad simple"};
        String[] modality = {"","Prueba de umbral","Edad corregida","Intensidad simple","Sensibilidad foveal","Sensibilidad no macular","Valor elegido por usuario"};
        return modality;
    }
    
    public ArrayList<String> getTestModeCID(String TestMode){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4232
        String[] TestMode_list = {"","Edad corregida","Prueba de umbral","Intensidad simple","Sensibilidad foveal","Sensibilidad no macular","Valor escogido por usuario"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(TestMode_list));

        // Search for element in list
        int index = match_list.indexOf(TestMode);

        String[] CSD_list = {"","DCM","DCM","DCM","DCM","DCM","DCM"};
        String[] CV_list =  {"","111838","111839","111840","111841","111842","121410"};
        String[] CM_list =  {"","Age corrected","Threshold related","Single luminance",
                            "Foveal sensitivity related","Related to non macular sensitivity","User chosen value"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.911";
        System.out.println("TestMode: "+TestMode+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);        
        return CID;
    }

    public String[] getFixationMonitor(){
        // Lista de modalidades con las que nos vamos a encontrar.
        // CID 4233
        //String[] modality = {"","Mirada/Punto ciego","Seguimiento de la mirada","Mancha ciega","Apagado"};
        String[] modality = {"","Mirada/Punto ciego","Seguimiento de la mirada","Mancha ciega","Apagado","Observación por el examinador"};
        return modality;
    }
    
    public ArrayList<String> getFixationMonitorCID(String FixationMonitor){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4233
        String[] list = {"","Seguimiento de la mirada","Mirada/Punto ciego","Mancha ciega","Observación por el examinador","Apagado"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(FixationMonitor);

        String[] CSD_list = {"","DCM","DCM","DCM","DCM","SRT"};
        String[] CV_list =  {"","111843","111844","111845","111846","R-40775"};
        String[] CM_list =  {"","Automated Optical","Blind Spot Monitoring","Macular Fixation Testing",
                            "Observation by Examiner","None"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.912";
        System.out.println("FixationMonitor: "+FixationMonitor+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);        
        return CID;
    }
    
    public String[] getConceptName(){
        // CID 4237
        String[] modality = {"","Prueba de hemicampo en glaucoma (PHG)","Índice del campo visual","Pérdida de campo visual debida a defecto difuso","Pérdida de campo visual debida a defecto local","Mediciones de la fijación óptica"};
        return modality;
    }
    
    public ArrayList<String> getConceptNameCID(String TestStrategy){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4237
        String[] list = {"","Índice del campo visual","Pérdida de campo visual debida a defecto difuso","Pérdida de campo visual debida a defecto local","Prueba de hemicampo en glaucoma (PHG)","Mediciones de la fijación óptica"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(TestStrategy);

        String[] CSD_list = {"","DCM","DCM","DCM","DCM","DCM"};
        String[] CV_list =  {"","111852","111853","111854","111855","111856"};
        String[] CM_list =  {"","Visual Field Index","Visual Field Loss Due to Diffuse Defect","Visual Field Loss Due to Local Defect","Glaucoma Hemifield Test Analysis","Optical Fixation Measurements"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.916";
        System.out.println("TestStrategy: "+TestStrategy+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);        
        return CID;
    }
    
    /*public String[] getFixationTarget(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","Central","Diamante pequeño","Diamante grande","LED interior"};
        return modality;
    }*/

    public String[] getFovealThresold(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","Apagado","Encendido"};
        return modality;
    }

    public String[] getFluctuation(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","Apagado","Encendido"};
        return modality;
    }
    
    public String[] getStimulusSize(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","I","II","III","IV","V"};    // III By default.
        return modality;
    }

    public String[] getStimulusColor(){
        // Lista de modalidades con las que nos vamos a encontrar.
        // CID 4235
        //String[] modality = {"","Blanco","Azul"};
        String[] modality = {"","Blanco","Azul","Rojo"};
        return modality;
    }

    public String[] getBackgroundColor(){
        // Lista de modalidades con las que nos vamos a encontrar.
        // CID 4235
        //String[] modality = {"","Blanco","Amarillo"};
        String[] modality = {"","Blanco","Amarillo"};
        return modality;
    }
    
    public ArrayList<String> getColorCID(String Color){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4235
        String[] list = {"","Amarillo","Blanco","Rojo","Azul","Verde"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(Color);

        String[] CSD_list = {"","SRT","SRT","SRT","SRT","SRT"};
        String[] CV_list =  {"","G-A11D","G-A12B","G-A11A","G-A12F","G-A11E"};
        String[] CM_list =  {"","Yellow","White","Red","Blue","Green"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.914";

        System.out.println("Color: "+Color+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);
        return CID;
    }
    
    public String[] getBackgroundLuminance(){
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","4","31.5","100","1000"};
        return modality;
    }
    
    public String[] getVisualAcuity(){ // UNUSED
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","No percibe luz","Percibe luz","Movimiento de manos","Cuenta dedos","0.1","0.2","0.3","0.4","0.5","0.6","0.7","0.8","0.9","1.0"};
        return modality;
    }
     
    public String[] getAnatomy(){  // UNUSED
        // Lista de modalidades con las que nos vamos a encontrar.
        String[] modality = {"","Retina","Arteria oftálmica","Cabeza del nervio óptico","Cámara anterior del ojo","Ambos ojos","Coroides del ojo","Cuerpo ciliar","Conjuntiva","Córnea","Ojo","Párpado","Fovea centralis","Iris","Carúncula lagrimal","La glándula lagrimal","Saco lagrimal","Lente","Párpado inferior","Esclerótica","Párpado superior"};
        return modality;
    }
    
    public String[] getPHG(){
        // Lista de modalidades con las que nos vamos a encontrar.
        // CID 4234
        //String[] modality = {"","Dentro de los límites normales","Fuera de los límites normales","Dudoso"};
        String[] modality = {"","Dentro de los límites normales","Fuera de los límites normales","Dudoso","Sensibilidad anormalmente alta","Reducción general de sensibilidad","Reducción de sensibilidad en borde y general"};
        return modality;
    }
    
    public ArrayList<String> getConceptCID(String value){
        ArrayList<String> CID = new ArrayList<String>();    // CID 4234
        String[] list = {"","Fuera de los límites normales","Dudoso","Sensibilidad anormalmente alta","Reducción general de sensibilidad","Reducción de sensibilidad en borde y general","Dentro de los límites normales"};
        ArrayList<String> match_list = new ArrayList(Arrays.asList(list));

        // Search for element in list
        int index = match_list.indexOf(value);

        String[] CSD_list = {"","DCM","DCM","DCM","DCM","DCM","SRT"};
        String[] CV_list =  {"","111847","111848","111849","111850","111851","M-00101"};
        String[] CM_list =  {"","Outside normal limits","Borderline","Abnormally high sensitivity",
                            "General reduction in sensitivity","Borderline and general reduction in sensitivity","Within normal limits"};

        String CSD = CSD_list[index];
        String CV = CV_list[index];
        String CM = CM_list[index];
        String UID = "1.2.840.10008.6.1.913";

        System.out.println("Value: "+value+" >CSD: "+CSD+" >CV:"+CV+" >CM:"+CM);

        CID.add(CSD);
        CID.add(CV);
        CID.add(CM);
        CID.add(UID);
        return CID;
    }

    /* UNUSED:
    public ArrayList<String> getWorklistAttributeTags(ArrayList<String> attributeNames) {
        ArrayList<String> attributeTags = new ArrayList<String>();
        String currentName;
        String[] nameList = {"Id", "AccessionNumber", "RequestedProcedureID", "RequestedProcedureCodeSequence", "RequestedProcedureDescription",
                            "ScheduledProcedureStepID", "ScheduledProcedStepProtocCode", "ScheduledProcedStepDescription",
                            "ScheduledProcedureStepDate", "ScheduledProcedureStepTime", "RequestingPhysician", "ImageLaterality"}; // Worklist Key list.
        ArrayList<String> match_list = new ArrayList(Arrays.asList(nameList));
        
        for(int i=0;i<attributeNames.size();i++){
            currentName = attributeNames.get(i);
            System.out.println("CurrentName: "+currentName);
            int index = match_list.indexOf(currentName);

            Integer[] tagList = {0x0,0x00080050,0x00401001,0x00321064,0x00321060,   // RequestedProcedureCodeSequence:0x00321064
                                0x00400009,0x00400008,0x00400007,                   // ScheduledProcedStepProtocCode:0x00400008
                                0x00404005,0x00321032};                             // RequestingPhysician:0x00321032

            String tag = Integer.toHexString(tagList[index]);
            attributeTags.add(tag);
            //System.out.println("Current tag: "+tag);
        }
        System.out.println("AttributeNames: "+attributeNames+"\nAttributeTags: "+attributeTags);
        
        return attributeTags;
    }
    public ArrayList<String> getStudyAttributeTags(ArrayList<String> attributeNames) {
        ArrayList<String> attributeTags = new ArrayList<String>();
        String currentName;
        String[] nameList = {"Id", "StudyId", "StudyInstanceUID", "StudyDate", "SphericalLensPower_RightEye",
                            "SphericalLensPower_LeftEye", "CylinderLensPower_RightEye", "CylinderLensPower_LeftEye", "CylinderAxis_RightEye",
                            "CylinderAxis_LeftEye", "StudyDescription", "TestpatternsCodeSequence", "TestStrategyCodeSequence",
                            "ScreeningTestModeCodeSequence", "FixationMonitoringCodeSequence", "StimulusArea", "StimulusColorCodeSequence",
                            "BackgroundLuminance", "BackgroundIlluminationColorCodeSequence", "StudyComments", "Revised"}; // Key list.

        ArrayList<String> match_list = new ArrayList(Arrays.asList(nameList));

        for(int i=0;i<attributeNames.size();i++){
            currentName = attributeNames.get(i);
            int index = match_list.indexOf(currentName);

            Integer[] tagList = {0x0,0x00200010,0x0020000D,0x00080020,0x00220007,   // Left and right eye differenciation.
                                0x00220007,0x00220008,0x00220008,0x00220009,
                                0x00220009,0x00081030,0x00400260,0x00400260,        // TestpatternsCodeSequence&TestStrategyCodeSequence same Tag.
                                0x00240016,0x00240033,0x00240025,0x00240021,        // SQ how to get data (Code Value or Code meaning???).
                                0x00240020,0x00240024,0x00324000,0x0};

            String tag = Integer.toHexString(tagList[index]);
            attributeTags.add(tag);
            //System.out.println("Current tag: "+tag);
        }
        System.out.println("AttributeNames: "+attributeNames+"\nAttributeTags: "+attributeTags);

        return attributeTags;
    }
    public ArrayList<String> getPatientAttributeTags(ArrayList<String> attributeNames) {
        ArrayList<String> attributeTags = new ArrayList<String>();
        String currentName;
        String[] nameList = {"Id", "PatientID", "PatientsName", "PatientsSurName",
                            "PatientsSex", "PatientsBirthDate", "PatientComments"}; // Patient Key list.
        ArrayList<String> match_list = new ArrayList(Arrays.asList(nameList));

        for(int i=0;i<attributeNames.size();i++){
            currentName = attributeNames.get(i);
            int index = match_list.indexOf(currentName);

            Integer[] tagList = {0x0,0x00100020,0x00100010,0x00100010,
                                0x00100040,0x00100030,0x00104000};   // PatientsName,PatientsSurName.

            String tag = Integer.toHexString(tagList[index]);
            attributeTags.add(tag);
            //System.out.println("Current tag: "+tag);
        }
        System.out.println("AttributeNames: "+attributeNames+"\nAttributeTags: "+attributeTags);

        return attributeTags;
    }
    public ArrayList<String> getPhysicianAttributeTags(ArrayList<String> attributeNames) {
        ArrayList<String> attributeTags = new ArrayList<String>();
        String currentName;
        String[] nameList = {"Id", "PhysicianId", "PerformingPhysiciansName","PerformingPhysiciansSurName"}; // Key list.
        ArrayList<String> match_list = new ArrayList(Arrays.asList(nameList));

        for(int i=0;i<attributeNames.size();i++){
            currentName = attributeNames.get(i);
            int index = match_list.indexOf(currentName);

            Integer[] tagList = {0x0,0x0,0x00081050,0x0};   // PerformingPhysiciansName,PerformingPhysiciansSurName.

            String tag = Integer.toHexString(tagList[index]);
            attributeTags.add(tag);
            //System.out.println("Current tag: "+tag);
        }
        System.out.println("AttributeNames: "+attributeNames+"\nAttributeTags: "+attributeTags);

        return attributeTags;
    }
    */
    
    private static final int SPECIFIC_CHARACTER_SET     = 0x80005;
    private static final int ACCESSION_NUMBER           = 0x80050;
    private static final int MODALITY                   = 0x80060;
    private static final int REFERRING_PHYSICIANS_NAME  = 0x80090;
    
    private static final int CODE_VALUE                 = 0x80100;
    private static final int CODING_SCHEME_DESIGNATOR   = 0x80102;
    private static final int CODE_MEANING               = 0x80104;
    private static final int CONTEXT_UID                = 0x80117;
    
    private static final int STUDY_DESCRIPTION          = 0x81030;  // Comments coming from specialist.
    
    private static final int PATIENTS_NAME              = 0x100010;
    private static final int PATIENT_ID                 = 0x100020;
    private static final int PATIENTS_BIRTH_DATE        = 0x100030;
    private static final int PATIENTS_SEX               = 0x100040;
    private static final int PATIENT_COMMENTS           = 0x104000;
        
    private static final int MEDICAL_ALERTS             = 0x102000;
    
    private static final int STUDY_INSTANCE_UID         = 0x20000D;
    private static final int LATERALITY                 = 0x200060;
    private static final int IMAGE_LATERALITY           = 0x200062;
    
    private static final int SCREENING_TEST_MODE_CODE_SEQUENCE     = 0x240016;
        /* SCREENING_TEST_MODE_CODE_SEQUENCE: 
        CONTEXT_UID = 1.2.840.10008.6.1.911
        private static final int CODE_VALUE                 = 0x80100;
        private static final int CODING_SCHEME_DESIGNATOR   = 0x80102;
        private static final int CODE_MEANING               = 0x80104;
        private static final int CONTEXT_UID                = 0x80117;*/
    private static final int MEASUREMENT_LATERALITY     = 0x240113;
    
    
    private static final int REQUESTING_PHYSICIAN                   = 0x321032;    
    private static final int REQUESTED_PROCEDURE_DESCRIPTION        = 0x321060;
    private static final int REQUESTED_PROCEDURE_CODE_SEQUENCE      = 0x321064;
    private static final int STUDY_COMMENTS                         = 0x324000; // Not used.
    
    private static final int SCHEDULED_STATION_AE_TITLE             = 0x400001;
    private static final int SCHEDULED_PROCEDURE_STEP_START_DATE    = 0x400002;
    private static final int SCHEDULED_PROCEDURE_STEP_START_TIME    = 0x400003;
    private static final int SCHEDULED_PROTOCOL_CODE_SEQUENCE       = 0x400008;    
    private static final int SCHEDULED_PROCEDURE_STEP_ID            = 0x400009;
    
    private static final int SCHEDULED_STATION_NAME                 = 0x400010;
    private static final int SCHEDULED_PROCEDURE_STEP_SEQUENCE      = 0x400100;
    private static final int PERFORMED_PROTOCOL_CODE_SEQUENCE       = 0x400260;
        private static final int PROTOCOL_CONTEXT_SEQUENCE          = 0x400440;
        /*  TEST_PATTERNS_CODE_SEQUENCE:  
            CONTEXT_UID = 1.2.840.10008.6.1.909
            private static final int CODE_VALUE                 = 0x80100;
            private static final int CODING_SCHEME_DESIGNATOR   = 0x80102;
            private static final int CODE_MEANING               = 0x80104;
            private static final int CONTEXT_UID                = 0x80117;

            TEST_STRATEGY_CODE_SEQUENCE:  
            CONTEXT_UID = 1.2.840.10008.6.1.910
            private static final int CODE_VALUE                 = 0x80100;
            private static final int CODING_SCHEME_DESIGNATOR   = 0x80102;
            private static final int CODE_MEANING               = 0x80104;
            private static final int CONTEXT_UID                = 0x80117;
         */
    private static final int REQUESTED_PROCEDURE_ID             = 0x401001;
    
    private static final int PLACER_ORDER_NUMBER        = 0x402016;
    private static final int FILLER_ORDER_NUMBER        = 0x402017;
    
    
    
    public ArrayList<DB2Hash> processReferral(DB2Hash referralNote) {
        System.out.println("Entering processReferral function");
        ArrayList<DB2Hash> result = new ArrayList<DB2Hash>();
        
        DB2Hash patient2db = new DB2Hash();
        DB2Hash worklist2db = new DB2Hash();
        DB2Hash study2db = new DB2Hash();
        DB2Hash acquisition2db = new DB2Hash();        
        
        while(referralNote.size() > 0){ // We'll delete an attribute each loop.
            //System.out.println("Attributes in referral note: "+referralNote.size());
            Integer tag = Integer.parseInt(referralNote.keys().nextElement(), 16);  // Hexadecimal to int.
            String value = referralNote.elements().nextElement();
            System.out.println("Tag: "+Integer.toHexString(tag)+" Value: "+value);
            referralNote.values().remove(value);
            
            switch(tag){
                case(SPECIFIC_CHARACTER_SET): // Unused.
                    break;          

                case(ACCESSION_NUMBER): worklist2db.set("AccessionNumber", value);
                    break;          

                case(MODALITY): // Unused: attribute specific to this device.
                    break;          

                case(REFERRING_PHYSICIANS_NAME): worklist2db.set("RequestingPhysician", value); // Considered the same as Requesting Physician.
                    break;          

                case(STUDY_DESCRIPTION): study2db.set("StudyDescription", value);
                    break;          

                case(PATIENTS_NAME):    ArrayList<String> DICOMname = FL.getName(value,"^");
                                        System.out.println("DICOMname: "+DICOMname);
                                        patient2db.set("PatientsName", DICOMname.get(0));
                                        patient2db.set("PatientsSurName", DICOMname.get(1));
                    break;          

                case(PATIENT_ID): patient2db.set("PatientID", value);
                    break;          

                case(PATIENTS_BIRTH_DATE): patient2db.set("PatientsBirthDate", value);
                    break;          

                case(PATIENTS_SEX): patient2db.set("PatientsSex", value);
                    break;          

                case(MEDICAL_ALERTS): // Unused. 
                    break;          

                case(STUDY_INSTANCE_UID): study2db.set("StudyInstanceUID", value);
                                          study2db.set("StudyId", value);
                    break;          

                case(LATERALITY): acquisition2db.set("ImageLaterality", value);
                    break;          

                case(IMAGE_LATERALITY): acquisition2db.set("ImageLaterality", value);          // Considered the same as Image laterality.
                    break;          

                case(MEASUREMENT_LATERALITY): worklist2db.set("ImageLaterality", value);    // Considered the same as Image laterality.
                    break;          

                case(REQUESTING_PHYSICIAN): worklist2db.set("RequestingPhysician", value);  
                    break;          

                case(REQUESTED_PROCEDURE_DESCRIPTION): worklist2db.set("RequestedProcedureDescription", value);
                    break;          

                case(REQUESTED_PROCEDURE_CODE_SEQUENCE): worklist2db.set("RequestedProcedureCodeSequence", value);
                    break;          

                case(SCHEDULED_STATION_AE_TITLE):  // Unused: attribute specific to this device.
                    break;          

                case(SCHEDULED_PROCEDURE_STEP_START_DATE): worklist2db.set("ScheduledProcedureStepDate", value);
                    break;          

                case(SCHEDULED_PROCEDURE_STEP_START_TIME): worklist2db.set("ScheduledProcedureStepTime", value);
                    break;          

                case(SCHEDULED_PROCEDURE_STEP_ID): worklist2db.set("ScheduledProcedureStepID", value);
                    break;          

                case(SCHEDULED_STATION_NAME): // Unused: attribute specific to this device.
                    break;          

                case(SCHEDULED_PROCEDURE_STEP_SEQUENCE): 
                    break;          

                case(REQUESTED_PROCEDURE_ID): worklist2db.set("RequestedProcedureID", value);
                    break;          

                case(PLACER_ORDER_NUMBER): 
                    break;          

                case(FILLER_ORDER_NUMBER): 
                    break;          
                default:    System.out.println(">>> Attribute NOT found in list: "+Integer.toHexString(tag)+" Value: "+value);
                    break;
            }
            
        }
        result.add(patient2db);
        result.add(worklist2db);
        result.add(study2db);
        result.add(acquisition2db);        
        
        return result;
    }
}

    
